package com.zhangkang.stock.stocklib.view

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import com.zhangkang.stock.stocklib.data.KLineInfo
import com.zhangkang.stock.stocklib.tools.DecimalFormatTools

/**
 * @author : Android-张康
 * created on: 2023/5/9 18:19
 * description:
 */
internal class KLineKLine(
    private val pathPool: PathPool,
    private val rectPool: RectPool,
    private val kLineViewColor: KLineViewColor,
    private val kLineViewDimen: KLineViewDimen,
    private val indexNameConfig: IndexNameConfig
) : KLineIndexInfo {

    private val ma5LineInfo = object : IndexLineInfo {
        override fun getName(): String {
            return "MA5"
        }

        override fun getLineColor(): Int {
            return Color.parseColor("#282828")
        }

        override fun getIndexValue(kLineInfo: KLineInfo): Float {
            return kLineInfo.ma5
        }
    }

    private val ma10LineInfo = object : IndexLineInfo {

        override fun getName(): String {
            return "MA10"
        }

        override fun getLineColor(): Int {
            return Color.parseColor("#F5BE51")
        }

        override fun getIndexValue(kLineInfo: KLineInfo): Float {
            return kLineInfo.ma10
        }
    }

    private val ma20LineInfo = object : IndexLineInfo {

        override fun getName(): String {
            return "MA20"
        }

        override fun getLineColor(): Int {
            return Color.parseColor("#CE35DE")
        }

        override fun getIndexValue(kLineInfo: KLineInfo): Float {
            return kLineInfo.ma20
        }
    }


    private val indexLineInfoList = mutableListOf(
        ma5LineInfo,
        ma10LineInfo,
        ma20LineInfo
    )

    private val indexLineInfoPath = mutableMapOf<IndexLineInfo, Path>()

    private var maxValue: Float = 0F
    private var minValue: Float = 0F
    private var mMaxWithinRange: KLineInfo? = null
    private var mMinWithinRange: KLineInfo? = null

    private var priceItem: Float = 0.0F

    private var volumeWidth: Float = 0.0F

    private var kLinePath: Path? = null

    private var halfWidth: Float = 0.0F

    /**
     * 获取K线指标类型
     */
    override fun getKLineIndex(): KLineIndex {
        return KLineIndex.KLine
    }

    override fun getProportion(): Int {
        return 3
    }

    /**
     * 计算最大值前
     *
     * @param kLineInfo 第一个值
     */
    override fun calculationMaxAndMinBefore(kLineInfo: KLineInfo) {
        maxValue = kLineInfo.lowerPrice
        minValue = kLineInfo.highPrice
        mMaxWithinRange = kLineInfo
        mMinWithinRange = kLineInfo
    }

    /**
     * 计算最大值
     *
     * @param kLineInfo 当前值
     */
    override fun calculationMaxAndMin(kLineInfo: KLineInfo) {
        if (kLineInfo.highPrice > maxValue) {
            maxValue = kLineInfo.highPrice
            mMaxWithinRange = kLineInfo
        }
        if (kLineInfo.lowerPrice < minValue) {
            minValue = kLineInfo.lowerPrice
        }
        if (kLineInfo.lowerPrice < (mMinWithinRange?.lowerPrice ?: Float.MIN_VALUE)) {
            mMinWithinRange = kLineInfo
        }
        indexLineInfoList.forEach {
            val maValue = it.getIndexValue(kLineInfo)
            if (maValue > 0) {
                if (maValue > this.maxValue) {
                    this.maxValue = maValue
                } else if (maValue < this.minValue) {
                    this.minValue = maValue
                }
            }
        }
    }

    /**
     * 计算最大值后
     */
    override fun calculationMaxAndMinAfter() {

    }

    /**
     * 绘制背景
     *
     * @param canvas 画布
     * @param startX 开始X
     * @param startY 开始Y
     * @param stopX 结束X
     * @param stopY 结束Y
     * @param linePaint 画布
     * @param textPaint 画布
     */
    override fun drawBackground(
        canvas: Canvas,
        startX: Float,
        startY: Float,
        stopX: Float,
        stopY: Float,
        linePaint: Paint,
        textPaint: Paint
    ) {
        linePaint.strokeWidth = kLineViewDimen.borderLineStrokeWidth
        linePaint.color = kLineViewColor.borderLineLineColor
        linePaint.style = Paint.Style.STROKE
        //绘制边框的线
        val backgroundPath = pathPool.acquire()
        canvas.drawPath(backgroundPath.apply {
            reset()
            moveTo(startX, startY)
            lineTo(stopX, startY)
            lineTo(stopX, stopY)
            lineTo(startX, stopY)
            lineTo(startX, startY)
        }, linePaint)
        //绘制横线同时绘制纵坐标
        //每个分段对应的高
        val itemHeight = (stopY - startY) / 4
        val itemPrice = (maxValue - minValue) / 4
        val textStartX = startX + kLineViewDimen.textPaddingLine
        textPaint.apply {
            color = kLineViewColor.ordinateTextColor
            textSize = kLineViewDimen.ordinateTextSize
        }
        repeat(5) {
            val itemStopY = startY + itemHeight * it
            when (it) {
                0 -> {
                    val drawText = DecimalFormatTools.retainTwoDecimalPlaces(maxValue)
                    val textBoundsRect = rectPool.acquire()
                    textPaint.getTextBounds(drawText, 0, drawText.length, textBoundsRect)
                    canvas.drawText(
                        drawText,
                        textStartX,
                        itemStopY + textBoundsRect.height() + kLineViewDimen.textPaddingLine,
                        textPaint
                    )
                    rectPool.release(textBoundsRect)
                }

                4 -> {
                    val drawText = DecimalFormatTools.retainTwoDecimalPlaces(minValue)
                    canvas.drawText(
                        drawText,
                        textStartX,
                        itemStopY - kLineViewDimen.textPaddingLine,
                        textPaint
                    )
                }

                else -> {
                    canvas.drawLine(startX, itemStopY, stopX, itemStopY, linePaint)
                    val drawText =
                        DecimalFormatTools.retainTwoDecimalPlaces(maxValue - itemPrice * it)
                    canvas.drawText(
                        drawText,
                        textStartX,
                        itemStopY - kLineViewDimen.textPaddingLine,
                        textPaint
                    )
                }
            }
        }
        pathPool.release(backgroundPath)
    }

    /**
     * 绘制当前值
     */
    override fun drawCurrentIndexInfo(
        canvas: Canvas,
        startX: Float,
        startY: Float,
        stopX: Float,
        stopY: Float,
        linePaint: Paint,
        textPaint: Paint,
        marginTop: Float,
        span: Int,
        indexValueHorizontalSpace: Float,
        indexValueVerticalSpace: Float,
        kLineInfo: KLineInfo,
        kLineIsLine: Boolean
    ) {
        //先绘制指标名称
//        CanvasTools.drawIndicatorName(
//            canvas = canvas,
//            rectLeft = startX,
//            rectTop = startY,
//            linePaint = linePaint,
//            textPaint = textPaint,
//            rectPool = rectPool,
//            indicatorName = "成交量",
//            indexNameConfig = indexNameConfig
//        )
        textPaint.textSize = kLineViewDimen.indexValueTextSize
        var indicatorStart = 0F
        var drawTextInVerticalCenter = 0
        indexLineInfoList.forEach { maInfo ->
            val currentString = "${maInfo.getName()}:${maInfo.getIndexValue(kLineInfo)}"
            textPaint.color = maInfo.getLineColor()
            drawTextInVerticalCenter = CanvasTools.drawTextInVerticalCenter(
                canvas, indicatorStart, startY, stopY, currentString, textPaint, rectPool = rectPool
            )
            indicatorStart += drawTextInVerticalCenter + indexValueHorizontalSpace
            if (!kLineIsLine) {
                val indexPath = pathPool.acquire()
                indexLineInfoPath[maInfo] = indexPath
            }
        }
    }

    override fun beforeDrawItemContent(
        canvas: Canvas,
        startX: Float,
        startY: Float,
        stopX: Float,
        stopY: Float,
        paint: Paint,
        candlestickWidth: Float,
        candlestickWidthSpace: Float,
        kLineInfo: KLineInfo,
        kLineIsLine: Boolean
    ) {
        val volumeSpace: Float = if (kLineIsLine) {
            kLinePath = pathPool.acquire()
            0F
        } else {
            kLineViewDimen.volumeRectSpace
        }
        val valueRange = maxValue - minValue
        val drawHeight = stopY - startY
        priceItem = drawHeight / valueRange

        volumeWidth = candlestickWidth + candlestickWidthSpace - volumeSpace

        halfWidth = (stopX - startX) / 2
    }

    override fun drawItemContent(
        canvas: Canvas,
        startX: Float,
        startY: Float,
        stopX: Float,
        stopY: Float,
        textPaint: Paint,
        linePaint: Paint,
        kLineInfo: KLineInfo,
        isFirst: Boolean,
        yangLineIsFill: Boolean,
        totalTranslateX: Float,
        candlestickWidth: Float,
        halfCandlestickWidth: Float,
        kLineIsLine: Boolean
    ) {
        //最高价格的 Y 坐标
        val highPriceY = priceItem * (maxValue - kLineInfo.highPrice) + startY
        //开盘价格的 Y 坐标
        val openPriceY = priceItem * (maxValue - kLineInfo.openPrice) + startY
        //收盘价格的 Y 坐标
        val closePriceY = priceItem * (maxValue - kLineInfo.closePrice) + startY
        //最低价格的 Y 坐标
        val lowerPriceY = priceItem * (maxValue - kLineInfo.lowerPrice) + startY
        //Path 的横坐标
        var pathX = halfCandlestickWidth + totalTranslateX
        if (pathX < 0) {
            pathX = halfCandlestickWidth
        }
        indexLineInfoPath.forEach {
            val maValue = it.key.getIndexValue(kLineInfo)
            val maY = priceItem * (maxValue - maValue) + startY
            val path = it.value
            if (isFirst) {
                if (maY <= stopY) {
                    path.moveTo(pathX, maY)
                } else {
                    path.moveTo(pathX, stopY)
                }
            } else {
                if (maY <= stopY) {
                    path.lineTo(pathX, maY)
                }
            }
        }
        if (isFirst) {
            kLinePath?.moveTo(pathX, closePriceY)
        } else {
            kLinePath?.lineTo(pathX, closePriceY)
        }
        if (!kLineIsLine) {
            //绘制蜡烛图
            drawCandlestick(
                canvas,
                kLineInfo,
                highPriceY,
                lowerPriceY,
                closePriceY,
                openPriceY,
                candlestickWidth = candlestickWidth,
                linePaint = linePaint,
                yangLineIsFill = yangLineIsFill
            )
        }
        //绘制最高价格和最低价格
        drawMaxOrMinPrice(
            canvas,
            kLineInfo,
            totalTranslateX,
            halfWidth,
            highPriceY,
            lowerPriceY,
            mCandlestickWidth = candlestickWidth,
            textPaint = textPaint
        )
        //绘制除复权标识
        if (kLineInfo.adjustFlag) {
            textPaint.color = kLineViewColor.adjustColor
            textPaint.textSize = kLineViewDimen.adjustTextSize
            textPaint.isUnderlineText = true
            val mTextBoundsRect = rectPool.acquire()
            textPaint.getTextBounds("S", 0, 1, mTextBoundsRect)
            val textStartX = (candlestickWidth - mTextBoundsRect.width()) / 2
            canvas.drawText(
                "S",
                textStartX,
                stopY - kLineViewDimen.maxOrMinPriceTextPaddingLine,
                textPaint
            )
            textPaint.isUnderlineText = false
            rectPool.release(mTextBoundsRect)
        }
    }

    override fun afterDrawItemContent(canvas: Canvas, paint: Paint) {
        indexLineInfoPath.forEach {
            val maColor = it.key.getLineColor()
            val maPath = it.value
            paint.color = maColor
            canvas.drawPath(maPath, paint)
            pathPool.release(maPath)
        }
        indexLineInfoPath.clear()
        kLinePath?.let {
            paint.color = kLineViewColor.kLineIsLineColor
            canvas.drawPath(it, paint)
            pathPool.release(it)
            kLinePath = null
        }
    }

    /**
     * 绘制蜡烛图
     */
    private fun drawCandlestick(
        canvas: Canvas,
        kLineInfo: KLineInfo,
        highPriceY: Float,
        lowerPriceY: Float,
        closePriceY: Float,
        openPriceY: Float,
        candlestickWidth: Float,
        linePaint: Paint,
        yangLineIsFill: Boolean
    ) {
        //判断当前绘制的颜色
        val candlestickColor = if (kLineInfo.closePrice > kLineInfo.openPrice) {
            kLineViewColor.redColor
        } else if (kLineInfo.closePrice < kLineInfo.openPrice) {
            kLineViewColor.greenColor
        } else {
            kLineViewColor.grayColor
        }
        linePaint.color = candlestickColor
        //竖线的中间位置
        val middlePositionOfVerticalLine = candlestickWidth / 2
        //绘制竖线
        if (kLineInfo.closePrice <= kLineInfo.openPrice || yangLineIsFill) {
            linePaint.style = Paint.Style.FILL_AND_STROKE
            canvas.drawLine(
                middlePositionOfVerticalLine,
                highPriceY,
                middlePositionOfVerticalLine,
                lowerPriceY,
                linePaint
            )
        } else {
            linePaint.style = Paint.Style.STROKE
            //此处收盘价大于开盘价，先绘制最高价到收盘价之间的线，即上影线
            canvas.drawLine(
                middlePositionOfVerticalLine,
                highPriceY,
                middlePositionOfVerticalLine,
                closePriceY,
                linePaint
            )
            //再绘制开盘价到最低价之间的线，即下影线
            canvas.drawLine(
                middlePositionOfVerticalLine,
                openPriceY,
                middlePositionOfVerticalLine,
                lowerPriceY,
                linePaint
            )
        }
        //绘制中间方框
        if (kLineInfo.openPrice == kLineInfo.closePrice) {
            canvas.drawLine(0F, openPriceY, candlestickWidth, closePriceY, linePaint)
        } else {
            canvas.drawRect(0F, openPriceY, candlestickWidth, closePriceY, linePaint)
        }
    }

    /**
     * 绘制最高价和最低价
     */
    private fun drawMaxOrMinPrice(
        canvas: Canvas,
        kLineInfo: KLineInfo,
        totalTranslateX: Float,
        halfWidth: Float,
        highPriceY: Float,
        lowerPriceY: Float,
        mCandlestickWidth: Float,
        textPaint: Paint
    ) {
        if (mMinWithinRange == kLineInfo || mMaxWithinRange == kLineInfo) {
            textPaint.color = kLineViewColor.maxOrMinPriceTextColor
            textPaint.textSize = kLineViewDimen.ordinateTextSize
            if (mMaxWithinRange == kLineInfo) {
                val drawText: String = if (totalTranslateX > halfWidth) {
                    "${kLineInfo.highPrice} →"
                } else {
                    "← ${kLineInfo.highPrice}"
                }
                val textBoundsRect = rectPool.acquire()
                textPaint.getTextBounds(drawText, 0, drawText.length, textBoundsRect)
                val textY =
                    highPriceY + textBoundsRect.height() + kLineViewDimen.maxOrMinPriceTextPaddingLine
                val textX = if (totalTranslateX > halfWidth) {
                    -textBoundsRect.width() - mCandlestickWidth
                } else {
                    mCandlestickWidth
                }
                canvas.drawText(drawText, textX, textY, textPaint)
                rectPool.release(textBoundsRect)
            } else {
                val drawText: String = if (totalTranslateX > halfWidth) {
                    "${kLineInfo.lowerPrice} →"
                } else {
                    "← ${kLineInfo.lowerPrice}"
                }
                val textY = lowerPriceY - kLineViewDimen.maxOrMinPriceTextPaddingLine
                val textBoundsRect = rectPool.acquire()
                val textX = if (totalTranslateX > halfWidth) {
                    textPaint.getTextBounds(drawText, 0, drawText.length, textBoundsRect)
                    -textBoundsRect.width() - 3.0F
                } else {
                    mCandlestickWidth
                }
                canvas.drawText(drawText, textX, textY, textPaint)
                rectPool.release(textBoundsRect)
            }
        }
    }
}